package com.jzo2o.foundations.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.dto.response.ServeCategoryResDTO;
import com.jzo2o.foundations.model.dto.response.ServeSimpleResDTO;
import com.jzo2o.foundations.service.HomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Author mr.zhao
 * @Date 2025/7/3 15:59
 */
@Service
public class HomeServiceImpl implements HomeService {
	@Autowired
	private ServeMapper serveMapper;
	/**
	 * 首页服务列表
	 *
	 * @param regionId
	 * @return
	 */
	@Override
	@Caching(
			cacheable = {
					//如果结果无值,说明缓存穿透,则应设置缓存为空值,有效期为30分钟
					@Cacheable(unless = "#result.size()!=0",value = RedisConstants.CacheName.SERVE_ICON,key = "#regionId",cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES),
					//如果结果有值,则缓存不为空,有效期为永久
					@Cacheable(unless = "#result.size()==0",value = RedisConstants.CacheName.SERVE_ICON,key = "#regionId",cacheManager = RedisConstants.CacheManager.FOREVER)
			}
	)

	public List<ServeCategoryResDTO> firstPageServeList(Long regionId) {
		List<ServeCategoryResDTO> serveCateList = serveMapper.getServeTypeAndServeList(regionId);
		if (CollUtil.isEmpty(serveCateList)){
			return CollUtils.emptyList();
		}
		int cateSizeOriginal = serveCateList.size();
		int cateSize = cateSizeOriginal >= 2 ? 2 : cateSizeOriginal;
		//保留2个分类
		serveCateList = serveCateList.stream().limit(cateSize).collect(Collectors.toList());
		serveCateList.forEach(cate->{
			//保留每个分类下对应的4个服务项
			List<ServeSimpleResDTO> serveResDTOList = cate.getServeResDTOList();
			int serveSizeOriginal = serveResDTOList.size();
			int serveSize = serveSizeOriginal >= 4 ? 4 : serveSizeOriginal;
			List<ServeSimpleResDTO> serveListNew = serveResDTOList.stream().limit(serveSize).collect(Collectors.toList());
			cate.setServeResDTOList(serveListNew);
		});
		return serveCateList;
	}
}
